﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BattleShips.Common;
using TestServer;
using Finisar.SQLite;

namespace BattleShips.GameServers.CommandRunners {
    class Register : ICommandRunner {

        private SQLiteConnection sql_con;
        private SQLiteCommand sql_cmd;

        private void SetConnection() {
            sql_con = new SQLiteConnection
                ("Data Source=Database.db;Version=3;New=False;Compress=True;");
        }

        private void ExecuteQuery(string txtQuery) {
            SetConnection();
            sql_con.Open();
            sql_cmd = sql_con.CreateCommand();
            sql_cmd.CommandText = txtQuery;
            sql_cmd.ExecuteNonQuery();
            sql_con.Close();
        }

        public string RunCommand(Command command, GameClient client, GameServer server) {
            string[] userInfo = command.Argument.Split('-');
            string Username = userInfo[0];
            string Password = userInfo[1];
            SetConnection();
            sql_con.Open();
            string sql = "select * from users";
            SQLiteCommand cmd = new SQLiteCommand(sql, sql_con);
            SQLiteDataReader reader = cmd.ExecuteReader();
            while (reader.Read()) {
                if (Username.Equals(reader["username"].ToString())) {
                    reader.Close();
                    return "failed:0";
                }
            }
            RegisterNewPlayer(Username,Password);
            sql_con.Close();
            return "successful";
        }

        private void RegisterNewPlayer(string Username, string Password) {
            string registerQuery = "INSERT INTO users (id,username,password) VALUES(NULL,@user,@pass)";
            SQLiteCommand cmd2 = new SQLiteCommand(registerQuery, sql_con);
            cmd2.Parameters.Add("@user", Username);
            cmd2.Parameters.Add("@pass", Password);
            cmd2.ExecuteNonQuery();
        }
    }
}
